package mytest;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

public class SaveFile implements Runnable {
	private InputStream inputStream=null;
	public SaveFile ( InputStream inputStream ) {
		this.inputStream = inputStream;
	}
	
	 @Override
	    public void run()
	    {
	        try
	        {
	        	ObjectInputStream oi = new ObjectInputStream(this.inputStream);
				try {
					ArrayList<Person> persons2 = (ArrayList) oi.readObject();
					
					XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
					FileOutputStream file = new FileOutputStream("file.xml");
					XMLStreamWriter writer = xmlOutputFactory.createXMLStreamWriter(file);
					
					writer.writeStartElement("persons");
					for (int i = 0, lenI = persons2.size(); i < lenI; i++) {
						Person person = (Person) persons2.get(i);
						writer.writeStartElement("person");

						writer.writeStartElement("nume");
						writer.writeCharacters(person.getNume());
						writer.writeEndElement();

						writer.writeStartElement("prenume");
						writer.writeCharacters(person.getPrenume());
						writer.writeEndElement();

						writer.writeStartElement("age");
						writer.writeCharacters(Integer.toString(person.getAge()));
						writer.writeEndElement();

						writer.writeEndElement();
					}
					writer.writeEndElement();

				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (XMLStreamException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        catch (IOException e)
	        {
	            e.printStackTrace();
	        }
	    }
}
